﻿using MediatR;
using Service.Auth.Domain.AggregatesModel;
using Service.Auth.Domain.Events;
using Service.Core.Repository;
using Service.Framework;

namespace Service.Auth.Api.Application.DomainEventHandlers;
/// <summary>
/// 
/// </summary>
/// <param name="rolePermissionRepository"></param>
/// <param name="permissionRepository"></param>
public class RoleAddPermissionsDomainEventHandler(
    IRepository<RolePermission> rolePermissionRepository,
    IRepository<Permission> permissionRepository)
    : INotificationHandler<RoleAddPermissionsDomainEvent>
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="notification"></param>
    /// <param name="cancellationToken"></param>
    /// <exception cref="LogicErrorException"></exception>
    public async Task Handle(RoleAddPermissionsDomainEvent notification, CancellationToken cancellationToken)
    {
        //先删除之前的数据
        await rolePermissionRepository.DeleteAsync(s => s.RoleId.Equals(notification.RoleId), cancellationToken);
        var count = await permissionRepository.GetCount(s => notification.PermissionsIds.Contains(s.Id), cancellationToken);
        if (notification.PermissionsIds.Count != count)
            throw new LogicErrorException("菜单编号错误，请联系管理员。");
        var rolePermissions = notification.PermissionsIds.Select(s => new RolePermission(notification.RoleId, s)).ToList();
        await rolePermissionRepository.InsertRangeAsync(rolePermissions, cancellationToken);
    }
}
